﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;
using ICSharpCode.SharpZipLib.Zip;

namespace Super64
{
    public sealed class GameListManager : IEnumerable<GameListEntry>
    {
        private List<GameListEntry> m_GameCollection;

        public GameListManager()
        {
            m_GameCollection = new List<GameListEntry>();
        }

        public void Clear()
        {
            m_GameCollection.Clear();
        }

        public void GetRomList(string dirpath)
        {
            GameListEntry gameEntry;

            // Credit to @ruantec for this clever way of finding files
            string[] filters = new string[] {".z64", ".n64", ".v64", ".zip", ".bz2", ".7z"};
            foreach (string file in Directory.GetFiles(dirpath, "*.*", SearchOption.AllDirectories)
                .Where(u => filters.Contains(Path.GetExtension(u.ToLower()))).ToList())
            {

                switch(Path.GetExtension(file).ToLower())
                {
                    case ".zip": m_GameCollection.AddRange(ArchiveTools.GetZipEntries(file, filters)); continue;
                    case ".7z": m_GameCollection.AddRange(ArchiveTools.Get7zipEntries(file, filters)); continue;
                    case ".bz2": break;
                    default: break;
                }

                gameEntry = new GameListEntry(file, "", 0);
                string name = Path.GetFileNameWithoutExtension(file);

                // Filter out the any known file extension
                string[] parts = name.Split('.');

                if (parts.Length > 1)
                {
                    name = "";

                    foreach (string s in parts)
                    {
                        if (!filters.Contains("." + s))
                        {
                            name += s;
                        }
                        else
                        {
                            break;
                        }
                    }
                }

                gameEntry.Name = name;
                m_GameCollection.Add(gameEntry);
            }
        }

        public IEnumerator<GameListEntry> GetEnumerator()
        {
            return m_GameCollection.GetEnumerator();
        }

        System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator()
        {
            return m_GameCollection.GetEnumerator();
        }
    }
}
